﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Data;
using System.Globalization;
using System.IO.Compression;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using PmfWeb.Core.Errors;
using PmfWeb.Core.Utility;

namespace PmfWeb.Core.Web
{
    ///<summary>
    /// HttpContext对象上下文扩展  飘渺峰整理 2008-11-17
    ///</summary>
    public static class Current
    {
        #region "成员变量 HttpContext.Context"
        /// <summary>
        /// 当前上下文对象
        /// </summary>
        public static HttpContext Context = HttpContext.Current;
        #endregion

        #region "判断当前页面是否接收到了Post请求 public static bool IsPost()"
        /// <summary>
        /// 判断当前页面是否接收到了Post请求
        /// </summary>
        /// <returns>是否接收到了Post请求</returns>
        public static bool IsPost()
        {
            return HttpContext.Current.Request.HttpMethod.Equals("POST");
        }

        #endregion

        #region "判断当前页面是否接收到了Get请求 public static bool IsGet()"
        /// <summary>
        /// 判断当前页面是否接收到了Get请求
        /// </summary>
        /// <returns>是否接收到了Get请求</returns>
        public static bool IsGet()
        {
            return HttpContext.Current.Request.HttpMethod.Equals("GET");
        }

        #endregion

        #region "获取指定QueryParas方式传过来的参数值 public static string Get(string key)"
        /// <summary>
        /// 获取指定QueryParas方式传过来的参数值
        /// </summary>
        /// <param name="key">参数名</param>
        /// <returns>参数值</returns>
        public static string Get(string key)
        {
            return HttpContext.Current.Request.Params[key] ?? "";
        }

        /// <summary>
        /// 获取指定QueryParas方式传过来的参数值,可指定默认值及参数值最大长度
        /// </summary>
        /// <param name="key">参数名</param>
        /// <param name="iMax">参数最大长度</param>
        /// <param name="strDefault">默认值</param>
        /// <returns>参数值</returns>
        public static string Get(string key, int iMax, string strDefault)
        {
            return Get(key, iMax, strDefault, false);
        }

        /// <summary>
        /// 获取指定QueryParas方式传过来的参数值,可指定默认值及参数值最大长度
        /// </summary>
        /// <param name="key">参数名</param>
        /// <param name="iMax">参数最大长度</param>
        /// <param name="strDefault">默认值</param>
        /// <param name="isUrlDecode">是否对参数值进行UrlEncode解码</param>
        /// <returns>参数值</returns>
        public static string Get(string key, int iMax, string strDefault, bool isUrlDecode)
        {
            string result = Get(key);
            if (iMax <= 0) iMax = 8;
            if (0 == result.Length) return strDefault;
            if (isUrlDecode) result = HttpUtility.UrlDecode(result);
            if (iMax < result.Length) return result.Substring(0, iMax);
            return result;
        }

        /// <summary>
        /// 获取指定QueryParas方式传过来的参数值,并指定参数值最大长度,参数不存在或值超过最大长度,返回空字符串
        /// </summary>
        /// <param name="key">参数名</param>
        /// <param name="iMax">参数最大长度</param>
        /// <returns>参数值</returns>
        public static string Get(string key, int iMax)
        {
            return Get(key, iMax, "");
        }

        /// <summary>
        /// 获取指定QueryParas方式传过来的参数值,并指定默认值
        /// </summary>
        /// <param name="key">参数名</param>
        /// <param name="strDefault">默认值</param>
        /// <returns>获取值为空字符串时返回默认值</returns>
        public static string Get(string key, string strDefault)
        {
            string result = Get(key);
            if (0 == result.Length) return strDefault;
            return result;
        }

        /// <summary>
        /// 获取指定QueryParas方式传过来的参数值,并指定是否对参数值进行Url解码
        /// </summary>
        /// <param name="key">参数名</param>
        /// <param name="isUrlDecode">是否Url解码</param>
        /// <returns>Url解码后的参数值或未解码的参数值</returns>
        public static string Get(string key, bool isUrlDecode)
        {
            return isUrlDecode ? HttpUtility.UrlDecode(Get(key)) : Get(key);
        }

        ///<summary>
        /// 获取多个参数值数组(参数名为""的不获取)
        ///</summary>
        ///<param name="paras">参数名列表</param>
        ///<returns>参数值数组</returns>
        public static string[] GetArray(params string[] paras)
        {
            if (paras == null) throw new ArgumentNullException("paras");
            int iParas = paras.Length;
            List<string> result = new List<string>(iParas);
            for (int i = 0; i < iParas; i++)
            {
                if (Utils.ToEquals(paras[i], "")) continue;
                result.Add(Get(paras[i]));
            }
            return result.ToArray();
        }

        #endregion

        #region "获得当前页面的名称(不包含路径) public static string GetPageName()"
        /// <summary>
        /// 获得当前页面的名称(如:default.aspx)
        /// </summary>
        /// <returns>当前页面的名称</returns>
        public static string GetPageName()
        {
            string[] source = HttpContext.Current.Request.Url.AbsolutePath.Split('/');
            return source[source.Length - 1].ToLower();
        }
        #endregion

        #region "返回QueryString方式提交过来的参数数量 public static int GetParasCount()"
        /// <summary>
        /// 返回QueryString方式提交过来的参数数量
        /// </summary>
        /// <returns></returns>
        public static int GetParasCount()
        {
            return HttpContext.Current.Request.QueryString.Count;
        }
        #endregion

        #region "获取QueryString传递过来的参数整型值 public static int GetInt(string key)"
        ///<summary>
        /// 获取QueryString传递过来的参数正整型值,默认值为0
        ///</summary>
        ///<param name="key">变量名</param>
        ///<returns>整型参数值</returns>
        public static int GetInt(string key)
        {
            return GetInt(key, 0, Int32.MaxValue, 0);
        }
        #endregion

        #region "获取QueryString 方式传递过来的参数值数组 public static int[] GetInt(params string[] keys)"
        /// <summary>
        /// 获取QueryString 方式传递过来的参数值数组
        /// </summary>
        /// <param name="keys"></param>
        /// <returns></returns>
        public static int[] GetInt(params string[] keys)
        {
            int[] result = new int[keys.Length];
            for (int i = 0, j = keys.Length; i < j; i++)
            {
                result[i] = GetInt(keys[i], 0);
            }
            return result;
        }
        #endregion

        #region "获取字符串的前iMax位字符,超出部分添加"..." public static string GetMaxString(string str, int iMax)"
        /// <summary>
        /// 获取字符串的前iMax位字符,超出部分添加"..."
        /// </summary>
        /// <param name="str">要截取的字符串</param>
        /// <param name="iMax">最大长度</param>
        /// <returns>截取过的字符串</returns>
        public static string GetMaxString(string str, int iMax)
        {
            if (String.IsNullOrEmpty(str)) return "";
            return Utils.Left(str, iMax);
        }
        #endregion

        #region "获取QueryString传递过来的参数整型值,并指定参数范围和默认值. public static int GetInt(string key,int iMin, int iMax, int iDefault)"
        ///<summary>
        /// 获取QueryString传递过来的参数整型值
        ///</summary>
        ///<param name="key">参数名</param>
        ///<param name="iMin">最小值</param>
        ///<param name="iMax">最大值</param>
        ///<param name="iDefault">默认值</param>
        ///<returns>参数值</returns>
        public static int GetInt(string key, int iMin, int iMax, int iDefault)
        {
            return Utils.ToInt(Get(key), iMin, iMax, iDefault);
        }
        #endregion

        #region "获取QueryString传递过来的参数整型值,并指定默认值.public static int GetInt(string key, int iDefault)"
        /// <summary>
        /// 获取QueryString传递过来的参数整型值(值范围0---正无穷大),并指定默认值.
        /// </summary>
        /// <param name="key">参数名</param>
        /// <param name="iDefault">默认值</param>
        /// <returns>参数值</returns>
        public static int GetInt(string key, int iDefault)
        {
            return GetInt(key, 0, Int32.MaxValue, iDefault);
        }
        #endregion

        #region "获取POST方式提交过来的参数值,指定默认值"

        /// <summary>
        /// 获取POST方式提交过来的参数值,已过滤首尾空格
        /// </summary>
        /// <param name="key">参数名</param>
        /// <returns>参数值</returns>
        public static string Post(string key)
        {
            return (HttpContext.Current.Request.Form[key] ?? "").Trim();
        }


        /// <summary>
        /// 获取POST方式提交过来的参数值,不过滤首尾空格
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public static string PostNoTrim(string key)
        {
            return HttpContext.Current.Request.Form[key] ?? "";
        }

        ///<summary>
        /// 获取POST方式提交过来的参数值,并指定默认值
        ///</summary>
        ///<param name="key">key名字</param>
        ///<param name="strDefault">默认值</param>
        ///<returns>获取值为空字符串时返回默认值</returns>
        public static string Post(string key, string strDefault)
        {
            string result = Post(key);
            if (0 == result.Length) return strDefault;
            return result;
        }

        /// <summary>
        /// 获取POST方式提交过来的参数值,并指定是否对值进行HTML解码
        /// </summary>
        /// <param name="key">参数名</param>
        /// <param name="isEncode">是否编码</param>
        /// <returns>Html编码后的参数值或未编码的参数值</returns>
        public static string Post(string key, bool isEncode)
        {
            return isEncode ? Context.Server.HtmlDecode(Post(key)) : Post(key);
        }

        ///<summary>
        /// 获取POST方式提交过来的参数值,指定参数值的最大长度,大于该长度，则裁减字符串
        ///</summary>
        ///<param name="key">参数名</param>
        ///<param name="iMax">参数值的最大长度</param>
        ///<returns>大于该长度，则裁减字符串;反之,返回参数值</returns>
        public static string Post(string key, int iMax)
        {
            string result = Post(key);
            int i = result.Length;
            if (0 == i) return result;
            if (Math.Abs(iMax) < i)
                return result.Substring(0, iMax);
            return result;
        }

        ///<summary>
        /// 获取POST方式提交过来的参数值
        ///</summary>
        ///<param name="paras">参数名</param>
        ///<returns>参数值数组</returns>
        public static string[] PostArray(params string[] paras)
        {
            if (paras == null) throw new ArgumentNullException("paras");
            int iParas = paras.Length;
            List<string> result = new List<string>(iParas);
            for (int i = 0; i < iParas; i++)
            {
                if (Utils.ToEquals(paras[i], "")) continue;
                result.Add(Post(paras[i]));
            }
            return result.ToArray();
        }

        ///<summary>
        /// 获取Post方式提交过来的Int类型的值
        ///</summary>
        ///<param name="key">参数名</param>
        ///<param name="iDefault">参数值</param>
        ///<returns>获取到的参数值</returns>
        public static int PostInt(string key, int iDefault)
        {
            return Utils.ToInt(Post(key), iDefault);
        }
        /// <summary>
        /// 获取POST方式提交过来的参数整型值 public static int GetPostInt(string key)
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public static int PostInt(string key)
        {
            return Utils.ToInt(Post(key), 0, Int32.MaxValue, 0);
        }

        /// <summary>
        /// 获取POST方式提交过来的参数数量
        /// </summary>
        /// <returns></returns>
        public static int GetPostParasCount()
        {
            return HttpContext.Current.Request.Form.Count;
        }

        /// <summary>
        /// 获取POST方式提交过来的参数值,指定默认值
        /// </summary>
        /// <param name="key">参数名</param>
        /// <param name="fDefault">默认值</param>
        /// <returns>参数值</returns>
        public static float PostFloat(string key, float fDefault)
        {
            return Utils.ToFloat(Post(key), fDefault);
        }

        /// <summary>
        /// 获取POST方式传递过来的控件值数组(控件名字相同),并指定是否要包含空的值
        /// </summary>
        /// <param name="key">控件名</param>
        /// <param name="iskeepEmpty">是否保留空值</param>
        /// <returns>值数组</returns>
        public static string[] PostArray(string key, bool iskeepEmpty)
        {
            string temps = Post(key);
            if (0 == temps.Length) return new[] { "" };

            string[] array = temps.Split(new[] { ',' }, iskeepEmpty ? StringSplitOptions.None : StringSplitOptions.RemoveEmptyEntries);
            return array;
        }

        /// <summary>
        /// 获取POST方式传递过来的控件值数组(控件名字相同),并包含空的值
        /// </summary>
        /// <param name="key">控件名</param>
        /// <returns>值数组</returns>
        public static string[] PostArray(string key)
        {
            return PostArray(key, true);
        }

        /// <summary>
        /// 获取POST方式提交过来的参数值,获取失败返回0.0f
        /// </summary>
        /// <param name="key">参数名</param>
        /// <returns>参数值</returns>
        public static float PostFloat(string key)
        {
            return PostFloat(key, 0.0f);
        }

        /// <summary>
        /// 获取Post方式提交过来的Decimal类型的参数值
        /// </summary>
        /// <param name="key">参数名</param>
        /// <returns>存在该参数就返回参数值,反之,返回0.0m</returns>
        public static decimal PostDecimal(string key)
        {
            return PostDecimal(key, 0.0m);
        }

        /// <summary>
        /// 获取Post方式提交过来的Decimal类型的参数值,可以指定默认值
        /// </summary>
        /// <param name="key">参数名</param>
        /// <param name="dDefault">不存在该参数时返回的值</param>
        /// <returns>存在该参数就返回参数值,反之,返回默认值</returns>
        public static decimal PostDecimal(string key, decimal dDefault)
        {
            return Utils.ToDecimal(Post(key), dDefault);
        }

        /// <summary>
        /// 获取POST方式提交过来的参数值
        /// </summary>
        /// <param name="key">参数名</param>
        /// <param name="sDefault">默认值</param>
        /// <param name="iMax">值最大长度</param>
        /// <returns>返回参数值(超长就截取)</returns>
        public static string Post(string key, string sDefault, int iMax)
        {
            string result = Post(key);
            int i = result.Trim().Length;
            if (0 == i) return sDefault;
            if (iMax < i) return result.Substring(0, i);
            return result;
        }

        /// <summary>
        /// 获取POST方式提交过来日期时间类型的参数值
        /// </summary>
        /// <param name="key">参数名</param>
        /// <param name="dDefault">默认值</param>
        /// <returns>参数值</returns>
        public static DateTime PostDateTime(string key, DateTime dDefault)
        {
            return Utils.ToDateTime(Post(key), dDefault);
        }

        /// <summary>
        /// 获取Post提交过来的参数值(适用于radioButton列表),>0返回true;否则返回false public static bool GetPostBool(string key)
        /// </summary>
        /// <param name="key">参数名</param>
        /// <returns>参数值</returns>
        public static bool GetPostBool(string key)
        {
            return PostInt(key) > 0;
        }

        #endregion

        #region "获取POST或GET方式提交过来的参数值"
        ///<summary>
        /// 获取POST或Get方式提交过来的参数值(取值顺序:Request.QueryString、Request.Form、Request.ServerVariables和Request.Cookies)
        ///</summary>
        ///<param name="key">参数名</param>
        ///<returns>参数值</returns>
        public static string Paras(string key)
        {
            return Paras(key, "");
        }

        /// <summary>
        /// 获取POST或Get方式提交过来的参数值(取值顺序:Request.QueryString、Request.Form、Request.ServerVariables和Request.Cookies)
        /// </summary>
        /// <param name="key">参数名</param>
        /// <param name="iMax">参数值的最大长度</param>
        /// <returns>参数值</returns>
        public static string Paras(string key, int iMax)
        {
            string sValue = Paras(key);
            int i = sValue.Length;
            iMax = Math.Abs(iMax);
            if (0 == i) return "";
            if (i > iMax) return sValue.Substring(0, iMax);
            return sValue;
        }

        /// <summary>
        /// 获取POST或Get方式提交过来的参数值,并指定是否需要解码(取值顺序:Request.QueryString、Request.Form、Request.ServerVariables和Request.Cookies)
        /// </summary>
        /// <param name="key">参数名</param>
        /// <param name="isDecode">是否需要解码(UrlDecode)</param>
        /// <returns>参数值</returns>
        public static string Paras(string key, bool isDecode)
        {
            string sValue = Context.Request.Params[key] ?? "";
            if (isDecode) return Context.Server.UrlDecode(sValue);
            return sValue;
        }

        /// <summary>
        /// 获取POST或Get方式提交过来的参数值,并指定默认值(取值顺序:Request.QueryString、Request.Form、Request.ServerVariables和Request.Cookies)
        /// </summary>
        /// <param name="key">参数名</param>
        /// <param name="sDefault">默认值</param>
        /// <returns>如果参数名存在,返回其值,反之返回默认值</returns>
        public static string Paras(string key, string sDefault)
        {
            return Context.Request[key] ?? sDefault;
        }


        ///<summary>
        /// 获取POST或Get方式提交过来的参数的整数值,默认返回0;(取值顺序:Request.QueryString、Request.Form、Request.ServerVariables和Request.Cookies)
        ///</summary>
        ///<param name="key">参数名</param>
        ///<returns>参数值</returns>
        public static int ParasInt(string key)
        {
            return Utils.ToInt(Paras(key));
        }

        /// <summary>
        /// 获取POST或Get方式提交过来的参数的整数值,默认返回0;(取值顺序:Request.QueryString、Request.Form、Request.ServerVariables和Request.Cookies)
        /// </summary>
        /// <param name="key">参数名</param>
        /// <param name="iMin">参数值最小值</param>
        /// <param name="iMax">参数值最大值</param>
        /// <returns>参数值</returns>
        public static int ParasInt(string key, int iMin, int iMax)
        {
            return Utils.ToInt(Paras(key), iMin, iMax, 0);
        }
        /// <summary>
        /// 获取POST或Get方式提交过来的参数的整数值,指定默认返回值;(取值顺序:Request.QueryString、Request.Form、Request.ServerVariables和Request.Cookies)
        /// </summary>
        /// <param name="key">参数名</param>
        /// <param name="iMin">参数值最小值</param>
        /// <param name="iMax">参数值最大值</param>
        /// <param name="iDefault">默认返回值</param>
        /// <returns>参数值</returns>
        public static int ParasInt(string key, int iMin, int iMax, int iDefault)
        {
            return Utils.ToInt(Paras(key), iMin, iMax, iDefault);
        }

        /// <summary>
        /// 获取POST或Get方式提交过来的参数的整数值(参数值范围int类型的值范围),指定默认返回值;(取值顺序:Request.QueryString、Request.Form、Request.ServerVariables和Request.Cookies)
        /// </summary>
        /// <param name="key">参数名</param>
        /// <param name="iDefault">默认返回值</param>
        /// <returns>参数值</returns>
        public static int ParasInt(string key, int iDefault)
        {
            return Utils.ToInt(Paras(key), int.MinValue, int.MaxValue, iDefault);
        }

        /// <summary>
        /// 获取POST或Get方式提交过来的参数的整数值,默认返回0.0;(取值顺序:Request.QueryString、Request.Form、Request.ServerVariables和Request.Cookies)
        /// </summary>
        /// <param name="key">参数名</param>
        /// <returns>参数值</returns>
        public static float ParasFloat(string key)
        {
            return Utils.ToFloat(Paras(key));
        }
        #endregion

        /// <summary>
        /// 获取cookie信息
        /// </summary>
        /// <param name="key">cookie名称</param>
        /// <returns>cookie值</returns>
        public static string Cookie(string key)
        {
            return Cookie(key, "");
        }
        
        /// <summary>
        /// 获取cookie信息,可以指定默认值
        /// </summary>
        /// <param name="key">cookie名称</param>
        /// <param name="sDefault">默认值</param>
        /// <returns>cookie值</returns>
        public static string Cookie(string key, string sDefault)
        {
            HttpCookie cookie = Context.Request.Cookies[key];
            return null == cookie ? sDefault : cookie.Value;
        }

        #region "获得当前页面客户端的IP public static string GetIP()"
        /// <summary>
        /// 获得当前页面客户端的IP
        /// </summary>
        /// <returns>当前页面客户端的IP</returns>
        public static string GetIP()
        {
            string result = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
            if (string.IsNullOrEmpty(result))
            {
                result = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
            }

            if (string.IsNullOrEmpty(result))
            {
                result = HttpContext.Current.Request.UserHostAddress;
            }

            if (string.IsNullOrEmpty(result) || !PageValidate.IsIP(result))
            {
                return "127.0.0.1";
            }
            return result;
        }
        #endregion

        #region "返回指定的服务器变量信息 public static string GetServerVariable(string strName)"
        /// <summary>
        /// 返回指定的服务器变量信息
        /// </summary>
        /// <param name="strName">服务器变量名</param>
        /// <returns>服务器变量信息</returns>
        public static string GetServerVariable(string strName)
        {
            return Context.Request.ServerVariables[strName] ?? "";
        }
        #endregion

        #region "返回上一个页面的地址 public static string GetUrlReferrer()"
        /// <summary>
        /// 返回上一个页面的地址
        /// </summary>
        /// <returns>上一个页面的地址</returns>
        public static string GetUrlReferrer()
        {
            return GetUrlReferrer("");
        }

        /// <summary>
        /// 返回上一个页面的地址,可以指定一个默认要页面
        /// </summary>
        /// <param name="strDefault">默认页面</param>
        /// <returns>上一个页面地址</returns>
        public static string GetUrlReferrer(string strDefault)
        {
            string result = "";
            Uri uri = HttpContext.Current.Request.UrlReferrer;
            if (null != uri) result = uri.ToString();
            return String.IsNullOrEmpty(result) ? strDefault : result;
        }
        #endregion

        #region "得到当前完整主机头 public static string GetFullHost()"
        /// <summary>
        /// 得到当前完整主机头
        /// </summary>
        /// <returns>完整主机头字符串</returns>
        public static string GetFullHost()
        {
            HttpRequest request = HttpContext.Current.Request;
            if (!request.Url.IsDefaultPort)
            {
                return string.Format("{0}:{1}", request.Url.Host, request.Url.Port.ToString());
            }
            return request.Url.Host;
        }
        #endregion

        #region "获取主机头 public static string GetHost()"
        /// <summary>
        /// 得到主机头
        /// </summary>
        /// <returns></returns>
        public static string GetHost()
        {
            return HttpContext.Current.Request.Url.Host;
        }
        #endregion

        #region "获取当前请求的原始 URL(URL 中域信息之后的部分,包括查询字符串(如果存在)) public static string GetRawUrl()"
        /// <summary>
        /// 获取当前请求的原始 URL(URL 中域信息之后的部分,包括查询字符串(如果存在))
        /// </summary>
        /// <returns>原始 URL</returns>
        public static string GetRawUrl()
        {
            return HttpContext.Current.Request.RawUrl;
        }
        #endregion

        #region "判断当前访问是否来自浏览器软件 public static bool IsFromBrowser()"
        /// <summary>
        /// 判断当前访问是否来自浏览器软件
        /// </summary>
        /// <returns>当前访问是否来自浏览器软件</returns>
        public static bool IsFromBrowser()
        {
            string[] browserName = { "ie", "opera", "netscape", "mozilla", "konqueror", "firefox" };
            string curBrowser = HttpContext.Current.Request.Browser.Type.ToLower();
            for (int i = 0; i < browserName.Length; i++)
            {
                if (curBrowser.IndexOf(browserName[i]) >= 0)
                {
                    return true;
                }
            }
            return false;
        }
        #endregion

        #region "判断是否来自搜索引擎链接 public static bool IsFromSearchEngines()"
        /// <summary>
        /// 判断是否来自搜索引擎链接
        /// </summary>
        /// <returns>是否来自搜索引擎链接</returns>
        public static bool IsFromSearchEngines()
        {
            if (HttpContext.Current.Request.UrlReferrer == null)
            {
                return false;
            }
            string[] searchEngine = { "google", "yahoo", "msn", "baidu", "sogou", "sohu", "sina", "163", "lycos", "tom", "yisou", "iask", "soso", "gougou", "zhongsou" };
            string tmpReferrer = HttpContext.Current.Request.UrlReferrer.ToString().ToLower();
            for (int i = 0; i < searchEngine.Length; i++)
            {
                if (tmpReferrer.IndexOf(searchEngine[i]) >= 0)
                {
                    return true;
                }
            }
            return false;
        }
        #endregion

        #region "获取文件名 public static string GetFileName()"
        /// <summary>
        /// 获取文件名
        /// </summary>
        /// <returns>文件名字符串</returns>
        public static string GetFileName()
        {
            return System.IO.Path.GetFileName(HttpContext.Current.Request.Path);
        }
        #endregion

        #region "获得客户端操作系统类型 public static string GetClientOS"
        /// <summary>
        /// 获得操作系统
        /// </summary>
        /// <returns>操作系统名称</returns>
        public static string GetClientOS
        {
            get
            {
                if (HttpContext.Current.Request.UserAgent != null)
                {
                    string s = HttpContext.Current.Request.UserAgent.Trim().Replace("(", "").Replace(")", "");
                    string[] sArray = s.Split(';');
                    switch (sArray[2].Trim())
                    {
                        case "Windows 4.10":
                            s = "Windows 98";
                            break;
                        case "Windows 4.9":
                            s = "Windows Me";
                            break;
                        case "Windows NT 5.0":
                            s = "Windows 2000";
                            break;
                        case "Windows NT 5.1":
                            s = "Windows XP";
                            break;
                        case "Windows NT 5.2":
                            s = "Windows 2003";
                            break;
                        case "Windows NT 6.0":
                            s = "Windows Vista/Server 2008";
                            break;
                        case "Linux":
                            s = "Linux";
                            break;
                        default:
                            s = "Other";
                            break;
                    }
                    return s;
                }
                return "未知系统";
            }
        }
        #endregion

        #region "获取客户端浏览器类型及版本 public static string GetClientBrower"
        /// <summary>
        /// 获取客户端浏览器类型及版本
        /// </summary>
        public static string GetClientBrower
        {
            get
            {
                if (null != HttpContext.Current.Request.Browser)
                {
                    HttpRequest req = HttpContext.Current.Request;
                    string result = req.Browser.Browser.ToLower();
                    string s = req.Browser.Version;
                    switch (result)
                    {
                        case "applemac-safari":
                            return "谷歌浏览器" + s;
                        case "ie":
                            return "IE核心浏览器" + s;
                        case "firefox":
                            return "火狐浏览器" + s;
                        default:
                            break;
                    }
                }
                return "未知浏览器";
            }
        }
        #endregion

        #region "获取服务器操作系统 public static string GetServerOs"
        /// <summary>
        /// 获取服务器操作系统
        /// </summary>
        public static string GetServerOs
        {
            get
            {
                return Environment.OSVersion.VersionString;
            }
        }
        #endregion

        #region "获得当前完整Url地址 public static string GetUrl()"
        /// <summary>
        /// 获得当前完整Url地址
        /// </summary>
        /// <returns>当前完整Url地址</returns>
        public static string GetUrl()
        {
            return HttpContext.Current.Request.Url.ToString();
        }
        #endregion

        #region "回收应用程序池(需要高权限才能调用成功) public static void StartStopRecycleApp(string method, string appName)"
        //public static void StartStopRecycleApp(string method, string appName)
        //{
        //    string AppPoolName = appName;

        //    try
        //    {
        //        DirectoryEntry appPool = new DirectoryEntry("IIS://localhost/W3SVC/AppPools");
        //        DirectoryEntry findPool = appPool.Children.Getter(AppPoolName, "IIsApplicationPool");
        //        findPool.Invoke(method, null);
        //        appPool.CommitChanges();
        //        appPool.Close();
        //        lbMsg.Text = string.Format("应用程序池{0}{1}成功", AppPoolName, method);
        //    }
        //    catch (Exception ex)
        //    {
        //        lbMsg.Text = string.Format("应用程序池{0}{2}失败:{1}", AppPoolName, ex.Message, method);
        //    }
        //}
        #endregion

        #region "获取登陆用户UserID public static string GetLoginName"
        /// <summary>
        /// 获取登陆用户UserID,如果未登陆为0
        /// </summary>
        public static string GetLoginName
        {
            get
            {
                return HttpContext.Current.User.Identity.IsAuthenticated ? HttpContext.Current.User.Identity.Name : "";
            }
        }
        #endregion

        #region "设置页面不被缓存 public static void SetPageNoCache()"
        /// <summary>
        /// 设置页面不被缓存
        /// </summary>
        public static void SetPageNoCache()
        {
            HttpContext.Current.Response.Buffer = true;
            HttpContext.Current.Response.ExpiresAbsolute = DateTime.Now.AddSeconds(-1);
            HttpContext.Current.Response.Expires = 0;
            HttpContext.Current.Response.CacheControl = "no-cache";
            HttpContext.Current.Response.AddHeader("Pragma", "No-Cache");
        }
        #endregion

        #region "获取当前会话ID public static string GetSessionID()"
        /// <summary>
        /// 获取当前会话ID(注意:iframe和frameset会丢失Session)
        /// </summary>
        /// <returns>成功就返回Session ID,反之返回""</returns>
        public static string GetSessionID()
        {
            //iframe和frameset会丢失Session
            if (HttpContext.Current.Session != null) return HttpContext.Current.Session.SessionID;
            return "";
        }

        #endregion

        #region "长文章分页函数,输出文章页码 public static string ResponsePageSize(string source)"
        /// <summary>
        /// 长文章分页函数,输出文章页码
        /// </summary>
        /// <param name="source">文章字符串</param>
        /// <returns>页码字符串</returns>
        public static string ResponsePageSize(string source, string url, int iMaxLength, ref int pageCount)
        {
            string strRet = "";
            int pagesize = iMaxLength;  //文章每页大小 
            int intCurrentPage = 1;//设置第一页为初始页 
            int totalPage = 0;
            int totalCount = Utils.RemoveHtml(source).Length;//文章长度 

            if (pagesize < totalCount) //如果每页大小大于文章长度时就不用分页了 
            {
                if (totalCount % pagesize == 0)
                {
                    //设置总页数 
                    totalPage = totalCount / pagesize;
                }
                else
                {
                    //if the totalsize 
                    totalPage = totalCount / pagesize + 1;
                }
                pageCount = totalPage;

                //if (GETP["pages"] != null)
                //{//set Current page number 
                //try
                //{
                //处理不正常的地址栏的值 
                //m_intCurrentPage = Convert.ToInt32(Request.QueryString["pages"]);
                intCurrentPage = GetInt("p", 0);
                if (0 == intCurrentPage) intCurrentPage = 1;
                if (intCurrentPage > totalPage) intCurrentPage = totalPage;
                //}

                //catch
                //{
                //    m_intCurrentPage = m_intCurrentPage;
                //}
                //}

                //set the page content 设置获取当前页的大小 
                if (intCurrentPage < totalPage)
                {
                    pagesize = intCurrentPage < totalPage
                        ? pagesize : (totalCount - pagesize * (intCurrentPage - 1));
                    strRet += source.Substring(pagesize * (intCurrentPage - 1), pagesize);
                }
                else if (intCurrentPage == totalPage)
                {
                    int pageSize = totalCount - pagesize * (intCurrentPage - 1);
                    strRet += source.Substring(totalCount - pageSize);
                }

                string strPageInfo = " <p> </p>";
                for (int i = 1; i <= totalPage; i++)
                {
                    if (i == intCurrentPage)
                        strPageInfo += "第" + i + "页  ";
                    else
                        strPageInfo += " <a href=" + url
                            + "&p=" + i + ">" + i + " </a>&nbsp;&nbsp;";
                }
                //输出显示各个页码 
                //this.labPageNumber.Text = m_strPageInfo;
                return strPageInfo;
            }
            strRet += source;
            return strRet;
        }
        #endregion

        #region "显示当前错误 public static void ShowLastError()"
        /// <summary>
        /// 显示当前错误
        /// </summary>
        public static void ShowLastError()
        {
            if (null == Context.Server.GetLastError()) return;
            StringBuilder err = new StringBuilder("");
            err.AppendLine("<html><body style=\"font-size:14px;\">");
            err.AppendLine("www.5173.com Error:<br />");
            err.AppendFormat("<textarea name=\"errormessage\" style=\"width:80%; height:200px; word-break:break-all\">");
            err.AppendLine("出错信息:" + Context.Server.GetLastError().ToString());
            err.AppendLine("<textarea>");
            err.AppendLine("<body></html>");
            Context.Response.Write(err.ToString());
            Context.Response.End();
        }
        #endregion

        #region "判断是否是Repeater数据绑定的ItemTemplate或AlternatingItem行 public static bool IsRepeaterItem(RepeaterItemEventArgs e)"
        ///<summary>
        /// 判断Repeater对象数据行是否是ItemTemplate或AlternatingItem行
        ///</summary>
        ///<param name="e">RepeaterItemEventArgs对象</param>
        ///<returns>是返回true,反之返回false</returns>
        public static bool IsRepeaterItem(RepeaterItemEventArgs e)
        {
            return (ListItemType.Item == e.Item.ItemType || ListItemType.AlternatingItem == e.Item.ItemType);
        }
        #endregion

        #region "区域语言问题 public static CultureInfo ResolveCulture()"
        ///<summary>
        /// 解决区域语言问题
        ///</summary>
        ///<returns></returns>
        public static CultureInfo ResolveCulture()
        {
            string[] languages = Context.Request.UserLanguages;

            if (null == languages || 0 == languages.Length) return null;
            try
            {
                string language = languages[0].ToLowerInvariant().Trim();
                return CultureInfo.CreateSpecificCulture(language);
            }
            catch (ArgumentException)
            {
                return null;
            }
        }
        /// <summary>
        /// 解决区域问题
        /// </summary>
        /// <returns></returns>
        public static RegionInfo ResolveCountry()
        {
            CultureInfo info = ResolveCulture();
            if (null != info) return new RegionInfo(info.LCID);
            return null;
        }
        #endregion

        #region "HTTP压缩方法 public static void Compress()"
        /// <summary>
        /// HTTP压缩方法
        /// </summary>
        public static void Compress()
        {
            if (null == Context) return;
            if (IsEncodingAccepted("deflate"))  //不压缩
            {
                Context.Response.Filter = new DeflateStream(Context.Response.Filter, CompressionMode.Compress);
                SetEncoding("deflate");
            }
            else if (IsEncodingAccepted("gzip"))  //启用gzip压缩
            {
                Context.Response.Filter = new GZipStream(Context.Response.Filter, CompressionMode.Compress);
                SetEncoding("gzip");
            }
        }
        /// <summary>
        /// 判断是否支持压缩(gzip压缩)
        /// </summary>
        /// <param name="encoding">压缩方式</param>
        /// <returns>是否支持压缩</returns>
        private static bool IsEncodingAccepted(string encoding)
        {
            return null != Context.Request.Headers["Accept-encoding"] && Context.Request.Headers["Accept-encoding"].Contains(encoding);
        }
        /// <summary>
        /// 设置压缩类型
        /// </summary>
        /// <param name="encoding"></param>
        private static void SetEncoding(string encoding)
        {
            Context.Response.AddHeader("Content-encoding", encoding);
            Context.Response.Cache.VaryByHeaders["Accept-encoding"] = true;
        }
        #endregion

        #region "获取指定字符串的MD5密文 public static string GetMD5(string str)"
        ///<summary>
        /// 获取指定字符串的MD5密文
        ///</summary>
        ///<param name="str">要加密的字符串</param>
        ///<returns>密文字符串</returns>
        public static string GetMD5(string str)
        {
            return DESncrypt.GetMD5(str);
        }
        /// <summary>
        /// 获取指定字符串的MD5密文,可以指定MD5加密多次,最多3次
        /// </summary>
        /// <param name="str">要加密的字符串</param>
        /// <param name="iMax">加密的次数,最多3次</param>
        /// <returns>密文字符串</returns>
        public static string GetMD5(string str, int iMax)
        {
            if (iMax < 1) iMax = 1;
            if (iMax > 3) iMax = 3;
            string result = "";
            for (int i = 0; i < iMax; i++)
            {
                result = DESncrypt.GetMD5(str);
            }
            return result;
        }
        #endregion

        #region "写异常信息 public static void AddError()"
        /// <summary>
        /// 写异常信息
        /// </summary>
        public static void AddError()
        {
            // 在出现未处理的错误时运行的代码

            Exception objErr = HttpContext.Current.Server.GetLastError().GetBaseException();
            StringBuilder result = new StringBuilder("");

            result.AppendLine(String.Format("时间:{0},异常页面:{1},异常信息:{2},错误源:{3}", DateTime.Now.ToString(), Context.Request.Url,
                                        objErr.Message, objErr.Source));

            //string error = string.Empty;
            //string errortime = string.Empty;
            //string erroraddr = string.Empty;
            //string errorinfo = string.Empty;
            //string errorsource = string.Empty;
            //string errortrace = string.Empty;

            //error += "发生时间:" + System.DateTime.Now.ToString() + "<br>";
            //errortime = "发生时间:" + System.DateTime.Now.ToString();

            //error += "发生异常页: " + Context.Request.Url.ToString() + "<br>";
            //erroraddr = "发生异常页: " + Context.Request.Url.ToString();

            //error += "异常信息: " + objErr.Message + "<br>";
            //errorinfo = "异常信息: " + objErr.Message;

            ////error +="错误源:"+objErr.Source+"<br>";
            ////error += "堆栈信息:" + objErr.StackTrace + "<br>";
            //errorsource = "错误源:" + objErr.Source;
            //errortrace = "堆栈信息:" + objErr.StackTrace;
            //error += "--------------------------------------<br>";
            HttpContext.Current.Server.ClearError();
            //MediaTypeNames.Application["error"] = error;

            string str = "";

            //独占方式，因为文件只能由一个进程写入.
            System.IO.StreamWriter writer = null;
            try
            {
                lock (str)
                {
                    // 写入日志
                    string year = DateTime.Now.Year.ToString();
                    string month = DateTime.Now.Month.ToString();
                    string path = string.Empty;
                    string filename = DateTime.Now.Day.ToString() + ".txt";
                    //path = Server.MapPath("~/Error/") + year + "/" + month;

                    ErrorLoggerSection section =
                        System.Configuration.ConfigurationManager.GetSection("WebSiteErrorLogger") as
                        ErrorLoggerSection;
                    if (null == section) path = Context.Server.MapPath(@"~/log/");
                    if (section != null) path = Context.Server.MapPath(section.Path);

                    //如果目录不存在则创建
                    if (!System.IO.Directory.Exists(path))
                    {
                        System.IO.Directory.CreateDirectory(path);
                    }
                    System.IO.FileInfo file = new System.IO.FileInfo(path + "/" + filename);

                    writer = new System.IO.StreamWriter(file.FullName, true);//文件不存在就创建,true表示追加
                    writer.WriteLine("用户IP:" + Context.Request.UserHostAddress);


                    //writer.WriteLine(errortime);
                    //writer.WriteLine(erroraddr);
                    //writer.WriteLine(errorinfo);
                    //writer.WriteLine(errorsource);
                    //writer.WriteLine(errortrace);
                    writer.WriteLine(result.ToString());
                    writer.WriteLine("--------------------------------------------------------------------------------------");
                    //writer.Close();
                }
            }
            finally
            {
                if (writer != null)
                    writer.Close();
            }
            //Response.Redirect("~/Error/ErrorPage.aspx");
        }
        #endregion

        #region "获取当前内存中的缓存数据信息 public static string GetCacheDescription()"
        ///<summary>
        /// 获取当前内存中的缓存数据信息
        ///</summary>
        ///<returns></returns>
        public static string GetCacheDescription()
        {
            StringBuilder result = new StringBuilder("");
            IDictionaryEnumerator enumerator = HttpRuntime.Cache.GetEnumerator();
            while (enumerator.MoveNext())
            {
                result.Append(String.Format("名字:{0};类型:{1};值:{2}", enumerator.Key.ToString(),
                                            enumerator.Value.GetType().ToString(), enumerator.Value.ToString()));
                result.Append("<br/>");
            }
            return result.ToString();
        }
        #endregion

        #region "获取SEO关键字信息 public static string GetKeyWords(string key)"
        /// <summary>
        /// 获取SEO关键字信息(默认key名为:keywords)
        /// </summary>
        /// <returns></returns>
        public static string GetKeyWords(string key)
        {
            if (String.IsNullOrEmpty(key)) return Context.Server.HtmlDecode(ConfigHelper.GetString("keywords"));
            string result = ConfigHelper.GetString(key);
            if (0 == result.Length) return Context.Server.HtmlDecode(ConfigHelper.GetString("keywords"));
            return Context.Server.HtmlDecode(result);
        }

        /// <summary>
        /// SEO描述信息(默认key名为:description) public static string GetDescription(string key)
        /// </summary>
        /// <returns></returns>
        public static string GetDescription(string key)
        {
            if (String.IsNullOrEmpty(key)) return Context.Server.HtmlDecode(ConfigHelper.GetString("description"));
            string result = ConfigHelper.GetString(key);
            if (0 == result.Length) return Context.Server.HtmlDecode(ConfigHelper.GetString("description"));
            return Context.Server.HtmlDecode(result);
        }
        #endregion

        #region "弹出对话框 public static void AlertMessage(Page page, string errString)"
        /// <summary>
        /// 显示出错信息 飘渺峰添加 2009-02-23
        /// </summary>
        /// <param name="page"></param>
        /// <param name="errString"></param>
        public static void AlertMessage(Page page, string errString)
        {
            page.ClientScript.RegisterStartupScript(page.GetType(), Guid.NewGuid().ToString(),
                                                    "<script language='javascript' defer>alert('" + errString +
                                                    "');</script>");
        }
        /// <summary>
        /// 执行一段Javascript脚本
        /// </summary>
        /// <param name="page">执行的页面</param>
        /// <param name="js">要执行的javascript脚本</param>
        public static void JavaScript(Page page, string js)
        {
            page.ClientScript.RegisterStartupScript(page.GetType(), Guid.NewGuid().ToString(), js, true);
        }
        /// <summary>
        /// 弹出js提示框后,转到新地址去
        /// </summary>
        /// <param name="page">要执行的页面</param>
        /// <param name="msg">提示信息</param>
        /// <param name="replaceUrl">要转到的新地址</param>
        public static void AlertMessage(Page page, string msg, string replaceUrl)
        {
            string js = @"<script type='text/javascript' defer>alert('{0}');location.href='{1}';</script>";
            page.ClientScript.RegisterStartupScript(page.GetType(), Guid.NewGuid().ToString(), String.Format(js, msg, replaceUrl));
        }

        /// <summary>
        /// 弹出js提示框后,打开新窗口
        /// </summary>
        /// <param name="page">要执行的页面</param>
        /// <param name="msg">提示信息</param>
        /// <param name="newUrl">要打开新窗口的地址</param>
        public static void AlertNewMessage(Page page, string msg, string newUrl)
        {
            string js = @"<script type='text/javascript' defer>alert('{0}');window.open('{1}',"","");</script>";
            page.ClientScript.RegisterStartupScript(page.GetType(), Guid.NewGuid().ToString(), String.Format(js, msg, newUrl));
        }

        ///<summary>
        /// 弹出对话框(客户端javascript:alert(msg);)
        ///</summary>
        ///<param name="page">页面地址</param>
        ///<param name="msg">消息文字</param>
        public static void MessageBox(Page page, string msg)
        {
            AlertMessage(page,msg);
        }
        /// <summary>
        /// 提示用户确认对话框
        /// </summary>
        /// <param name="page">要执行的页面</param>
        /// <param name="msg">提示信息</param>
        /// <param name="url">要转的新地址,可以不填</param>
        public static void ConfirmMessage(Page page, string msg, string url)
        {
            StringBuilder builder = new StringBuilder();
            builder.Append("<script language='javascript' defer>");
            builder.AppendFormat("alert('{0}');", msg);
            if (!String.IsNullOrEmpty(url))
            {
                builder.AppendFormat("top.location.href='{0}'", url);
            }

            builder.Append("</script>");
            page.ClientScript.RegisterStartupScript(page.GetType(), Guid.NewGuid().ToString(), builder.ToString());
        }
        /// <summary>
        /// 注册调试Javascript脚本,适用于IE浏览器
        /// </summary>
        /// <param name="page">要调试js的页面对象</param>
        public static void DebugJavascript(Page page)
        {
            string key = "ie_debugby_pmf";

            if (page.ClientScript.IsClientScriptIncludeRegistered(key)) return;
            string url = @"http://getfirebug.com/releases/lite/1.2/firebug-lite-compressed.js";
            page.ClientScript.RegisterClientScriptInclude(key, url);
        }

        /// <summary>
        /// 注册客户端脚本
        /// </summary>
        /// <param name="page">页面对象</param>
        /// <param name="keyname">数组名</param>
        /// <param name="js">数组元素,可以是对象</param>
        public static void Register(Page page, string keyname, string js)
        {
            page.ClientScript.RegisterArrayDeclaration(keyname, js);
        }
        #endregion

        #region "其他"
        /// <summary>
        /// 判断用户是否已经登陆
        /// </summary>
        /// <returns>已登陆,返回true;反之,返回false</returns>
        public static bool IsLogin()
        {
            return !String.IsNullOrEmpty(GetLoginName);
        }

        /// <summary>
        /// 跳转
        /// </summary>
        /// <param name="response">HttpResponse对象</param>
        /// <param name="pathOrUrl">要跳转的地址</param>
        public static void RedirectPermanent(HttpResponse response, string pathOrUrl)
        {
            response.Clear();
            response.Status = "301 Moved Permanently";
            response.RedirectLocation = pathOrUrl;
            response.End();
        }

        ///<summary>
        /// 把IP地址转换成长整数
        ///</summary>
        ///<returns></returns>
        public static long IsRangeIp()
        {
            string ip = GetIP();
            if (0 == ip.Length) return 0L;
            string[] result = ip.Split('.');
            long lIP = 0;
            if (4 == result.Length)
            {
                lIP = (255 * 255 * 255 * int.Parse(result[0]) + 255 * 255 * int.Parse(result[1]) +
                       255 * int.Parse(result[2]) + int.Parse(result[3]));
            }
            return lIP;
        }
        #endregion

        #region "反射阅读器对象(DataReader)到实体类型"
        /// <summary>
        /// 反射阅读器对象(DataReader)到实体类型
        /// </summary>
        /// <typeparam name="T">实体类型</typeparam>
        /// <param name="reader">阅读器</param>
        /// <param name="target">实体类型</param>
        public static void DataReaderToObject<T>(IDataReader reader, T target)
        {
            System.Reflection.PropertyInfo propertyInfo;
            for (int i = 0, j = reader.FieldCount; i <j; i++)
            {
                propertyInfo = target.GetType().GetProperty(reader.GetName(i));
                if(null != propertyInfo && DBNull.Value != reader.GetValue(i))
                    propertyInfo.SetValue(target, reader.GetValue(i).ToString(), null);
            }
        }

        /// <summary>
        /// 反射阅读器对象(DataReader)到实体类型
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="reader"></param>
        /// <param name="target"></param>
        public static void DataReaderToObject<T>(IDataReader reader, List<T> target)
        {
            T obj;
            while (reader.Read())
            {
                obj = Activator.CreateInstance<T>();
                DataReaderToObject(reader, obj);
                target.Add(obj);
            }
        }
        #endregion


        ///<summary>
        /// 获取请求的Name-Value值对
        ///</summary>
        public static NameValueCollection RequestForms
        {
            get
            {
                return Context.Request.Form;
            }
        }
    }
}
